package com.hhkj.api.train.common.component.corrector;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.hhkj.admin.question.common.cont.QuestionTypeEnum;
import com.hhkj.admin.question.domain.Question;
import com.hhkj.admin.question.model.res.QuestionRes;
import com.hhkj.admin.train.common.cont.TrainConst;
import com.hhkj.admin.train.model.dopo.TrainPo;
import com.hhkj.admin.train.model.req.TrainReq;
import com.hhkj.admin.train.model.res.TrainRes;
import com.hhkj.admin.train.service.biz.TrainBizService;
import com.hhkj.api.common.session.holder.ApiStudentSessionHolder;
import com.hhkj.api.common.session.holder.model.LoginStudent;
import com.hhkj.api.train.common.bizutils.ApiTrainBizUtils;
import com.hhkj.api.train.common.utils.ApiQuestionCollectionConverter;
import com.hhkj.api.train.common.utils.ApiTrainCallBackUtils;
import com.hhkj.api.train.common.utils.CorrectUtils;
import com.hhkj.api.train.model.info.req.TrainSubmitReq;
import com.hhkj.api.train.model.info.res.ApiQuestionCorrectRes;
import com.hhkj.api.train.model.info.res.ApiQuestionRes;
import com.hhkj.api.train.model.info.res.TrainCorrectRes;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * ApiTrainCorrectFactory
 *
 * @author HHKJ-SERVER-ZJ
 * @since 2023/5/29 15:34
 */
@Slf4j
@Component
public class ApiTrainCorrector {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private TrainBizService trainBizService;
    @Autowired
    private ApiTrainBizUtils apiTrainBizUtils;

    /**
     * 获取学员作答阅卷信息
     *
     * @param trainId   培训id
     * @param studentId 学生id
     * @return 培训批改完信息
     */
    public TrainCorrectRes getStudentCorrectRes(Long trainId, Long studentId) {
        TrainPo trainPo = trainBizService.getPoById(trainId);
        if (ObjectUtil.isNull(trainPo) || !trainPo.getStudentId().equals(studentId)) {
            throw new GlobalException("数据为空，请刷新后重试");
        }
        TrainRes trainRes = BeanUtil.toBean(trainPo, TrainRes.class);
        apiTrainBizUtils.matchTrainQuestionList(trainRes);
        TrainCorrectRes trainCorrectRes = BeanUtil.toBean(trainRes, TrainCorrectRes.class);
        List<ApiQuestionRes> apiQuestionResList = ApiQuestionCollectionConverter.convertList(trainRes.getQuestionGroupList());
        trainCorrectRes.setQuestionList(BeanUtil.copyToList(apiQuestionResList, ApiQuestionCorrectRes.class));
        return trainCorrectRes;
    }

    /**
     * 批改培训信息
     *
     * @param req 请求信息
     * @return 批改结果信息
     */
    public TrainCorrectRes correctTrain(TrainSubmitReq req) {
        TrainReq trainReq = redisCache.getCacheObject(req.getTrainKey());
        if (ObjectUtil.isNull(trainReq)) {
            throw new GlobalException("培训信息已过期或者不存在！");
        }
        // 1-答案分组，取出题目组信息
        Map<Long, String> answerMapByQuestionId = req.getAnswerMapById();

        // 2-遍历题目组进行批改
        for (QuestionRes questionGroup : trainReq.getQuestionGroupList()) {
            if (QuestionTypeEnum.CASE.getCode().equals(questionGroup.getTypeCode())) {
                for (Question question : questionGroup.getQuestionList()) {
                    CorrectUtils.correctQuestion(question,
                            answerMapByQuestionId.getOrDefault(question.getId(), StrUtil.EMPTY));
                }
            } else {
                CorrectUtils.correctQuestion(questionGroup,
                        answerMapByQuestionId.getOrDefault(questionGroup.getId(), StrUtil.EMPTY));
            }
        }

        // 3-统计题目到train信息中
        CorrectUtils.countTrainQuestionCorrect(trainReq);

        // 4-统计培训分数
        if (TrainConst.Type.TEST.getCode().equals(trainReq.getTypeCode())) {
            CorrectUtils.countTrainCorrectMark(trainReq);
        }

        // 5-保存培训信息
        trainReq.setAnswerList(CorrectUtils.listStudentAnswerFromGroup(trainReq.getQuestionGroupList()));
        trainReq.setSubmitTime(new Date());
        int currentTimeDurationSecond = (int) DateUtil.between(trainReq.getStartTime(), trainReq.getSubmitTime(), DateUnit.SECOND);
        int lastTimeDurationSecond = ObjectUtil.isNull(trainReq.getDurationSecond()) ? 0 : trainReq.getDurationSecond();
        trainReq.setDurationSecond(lastTimeDurationSecond + currentTimeDurationSecond);
        if (ObjectUtil.isNull(trainReq.getId())) {
            trainBizService.insertTrain(trainReq);
        } else {
            trainBizService.updateTrain(trainReq);
        }
        redisCache.deleteObject(req.getTrainKey());

        LoginStudent loginStudent = ApiStudentSessionHolder.getLoginStudent();
        // 异步处理
        new Thread(() -> ApiTrainCallBackUtils.push(loginStudent, trainReq)).start();

        // 6-封装返回信息
        // List<QuestionRes> questionResList = ApiQuestionCollectionConverter.convertList(trainReq.getQuestionGroupList());
        // TrainCorrectRes trainCorrectRes = BeanUtil.toBean(trainReq, TrainCorrectRes.class);
        // trainCorrectRes.setQuestionList(BeanUtil.copyToList(questionResList, QuestionCorrectRes.class));
        return BeanUtil.toBean(trainReq, TrainCorrectRes.class);
    }


}
